package geekTime.chapter18StampedLock;

import java.util.concurrent.locks.StampedLock;

/**
 * 比读写锁性能更好的锁
 * Created by LinGer on 2019/7/1
 */
public class StampedLockTest {

    private int x, y;
    final StampedLock sl = new StampedLock();

    /**
     * 计算到圆点的距离
     * @return
     */
    public double distanceFromOrigin(){
        //乐观读
        long stamp = sl.tryOptimisticRead();
        //读入局部变量，读取过程中无锁，所以值可能被修改
        int curX = x, curY = y;
        //判断读取过程中是否存在写操作，如果存在sl.validate会返回false
        if(!sl.validate(stamp)){
            //升级为悲观锁
            stamp = sl.readLock();
            try {
                curX = x;
                curY = y;
            }finally {
                sl.unlockRead(stamp);
            }
        }

        return Math.sqrt(curX*curX + curY*curY);
    }
}
